<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="filters.name" placeholder="名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <org-unit-select v-model="filters.orgUnitId" placeholder="请选择店铺" :org-unit-type="1"/>
      <room-select v-model="filters.roomId" placeholder="请选择房间" :org-unit-id="filters.orgUnitId"/>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
      <div style="margin-left: 3.125rem;">
        <el-checkbox v-for="col in dynamicColumn.devices" v-model="col.show" class="filter-item" style="margin-left:10px;" @change="tableKey=tableKey+1">
          {{ col.name }}
        </el-checkbox>
      </div>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      border
      fit
      :height="tableHeight"
      :data="list"
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
      @selection-change="selsChange"
    >
      <el-table-column type="index" width="60" />
      <el-table-column prop="name" label="名称" min-width="220" />
      <el-table-column prop="code" label="设备码" min-width="320" />
      <el-table-column prop="orgUnitName" label="店铺" min-width="160" />
      <el-table-column prop="roomName" label="房间" min-width="160" />
      <el-table-column v-if="checkColumn('operation')" label="操作" width="220" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="small" @click="handleEdit(scope.index, scope.row)">编辑</el-button>
          <el-button v-if="canDeleteDevice" type="danger" size="small" @click="handleDelete(scope.index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="filters.page" :limit.sync="filters.limit" @pagination="loadPageList" />

    <!--新增界面-->
    <el-dialog title="设备信息" :visible.sync="addFormVisible" :close-on-click-modal="false">
      <el-form ref="addForm" :model="addForm" :label-width="formLabelWidth" :rules="addFormRules">
        <el-form-item label="名称" prop="name">
          <el-input v-model="addForm.name" auto-complete="off" />
        </el-form-item>
        <el-form-item v-if="!recordId" label="店铺">
          <org-unit-select ref="orgUnitAddSelect" placeholder="请选择店铺" :org-unit-type="1" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取消</el-button>
        <el-button type="primary" :loading="addLoading" @click="addSubmit">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDevice, modifyDevice, deleteDevice } from '@/api/devices'
import OrgUnitSelect from '../components/org-unit-select'
import RoomSelect from '../components/room-select'
import waves from '@/directive/waves' // waves directive
import { mapGetters } from 'vuex'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'Devices',
  components: { Pagination, OrgUnitSelect, RoomSelect },
  directives: { waves },
  data() {
    return {
      tableHeight: 260,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      sels: [], // 列表选中列
      filters: {
        page: 1,
        limit: 20,
        name: '',
        orgUnitId: null,
        roomId: null
      },
      orderBy: {
        orderColumn: '',
        order: ''
      },

      // 新增界面是否显示
      addFormVisible: false,
      addLoading: false,
      addFormRules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      },
      // 新增界面数据
      recordId: 0,
      addForm: {
        name: ''
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'formLabelWidth', 'dynamicColumn']),
    canDeleteDevice() {
      const roles = this.userInfo.roles || []
      if (roles.indexOf('Admin') !== -1) {
        return true
      }
      if (roles.indexOf('Manager') !== -1) {
        if (this.userInfo.orgUnitType === 2) {
          // 加盟商
          return true
        }
      }
      return false
    }
  },
  created() {
    this.tableHeight = window.innerHeight - 220
    this.loadPageList()
  },
  methods: {
    checkColumn(col) {
      if (this.dynamicColumn.devices.hasOwnProperty(col)) {
        return this.dynamicColumn.devices[col].show
      }
      return true
    },
    loadPageList() {
      this.listLoading = true
      const param = { ...this.filters, ...this.orderBy }
      listDevice(param).then(({ success, message, data }) => {
        this.listLoading = false
        if (success) {
          const { records, total } = data || {}
          this.list = records
          this.total = total
        } else {
          this.$message({
            message: message || '查询列表失败',
            type: 'error'
          })
        }
      }, () => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.filters.page = 1
      this.loadPageList()
    },
    sortChange({ prop, order }) {
      this.orderBy.orderColumn = prop
      this.orderBy.order = order
      this.handleFilter()
    },
    selsChange(sels) {
      this.sels = sels
    },
    handleEdit(index, row) {
      this.addFormVisible = true
      this.recordId = row.id
      this.addForm.name = row.name
      this.$nextTick(() => {
        this.$refs['addForm'].clearValidate()
      })
    },
    // 新增
    addSubmit: function() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true
            if (this.recordId) {
              this.doEdit()
            }
          })
        }
      })
    },
    doEdit() {
      modifyDevice(this.recordId, this.addForm).then(({ success, message }) => {
        this.addLoading = false
        if (success) {
          this.$message({
            message: message || '提交成功',
            type: 'success'
          })
          this.$refs['addForm'].resetFields()
          this.addFormVisible = false
          this.loadPageList()
        } else {
          this.$message({
            message: message || '添加失败',
            type: 'error'
          })
        }
      }, () => {
        this.addLoading = false
      })
    },
    handleDelete(index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        deleteDevice(row.id).then(({ success, message }) => {
          this.listLoading = false
          if (success) {
            this.$message({
              message: message || '删除成功',
              type: 'success'
            })
            this.loadPageList()
          } else {
            this.$message({
              message: message || '删除失败',
              type: 'error'
            })
          }
        }, (res) => {
          this.listLoading = false
        })
      }).catch(() => {

      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
